package com.sfx.算法专题.记忆化搜索;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: sfx
 * Date: 2023-09-28
 * Time: 8:23
 */
public class Code_1_fib {
    /**
     * 记忆化搜索版本的斐波那契数
     */
    static class Solution {

        private int[] memo;
        private int dfs(int n) {
            // 记忆化
            if (memo[n] != -1) {
                // 如果有,直接返回
                return memo[n];
            }
            if (n == 0 || n == 1) {
                // 记录一下
                memo[n] = n;
                return n;
            }
            int fib = dfs(n - 1) + dfs(n - 2);
            // 记录一下
            memo[n] = fib;
            return fib;
        }

        public int fib(int n) {
            memo = new int[n + 1];
            Arrays.fill(memo, -1);
            return dfs(n);
        }
    }
}